package com.bigtotoro.shuiyincamera.video;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.RectF;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigtotoro.shuiyincamera.BaseActivity;
import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMark2Activity;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMarkActivity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.view.CropImageView;
import com.umeng.analytics.MobclickAgent;

//import VideoHandle.EpEditor;
//import VideoHandle.OnEditorListener;
import io.microshow.rxffmpeg.RxFFmpegInvoke;
import io.microshow.rxffmpeg.RxFFmpegSubscriber;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

public class VideoRemoveWaterActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "main";
    private FrameLayout frameLayout;
    private VideoView videoView;
    private CropImageView cropView;

    int frameWidth, frameHeight;
    int videoWidth, videoHeight, videoRotation, videoDuration;
    private String path = "/storage/emulated/0/dakashuiyin/video/slice/1553506380742.mp4"; // 3s
    private String out;
    private float scale;
    private float videoX, videoY;
    private ProgressDialog mProgressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_remove_water);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

        //添加友盟事件统计
        MyUtils.addUmengEvent(VideoRemoveWaterActivity.this,"video_remove_watermark","视频去水印");
        initBase();

        path = getIntent().getStringExtra("path");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(this);

        VideoUtil.checkVideoDir();
        frameLayout = findViewById(R.id.frame);
        videoView = findViewById(R.id.video);
        cropView = findViewById(R.id.crop);

        videoView.setVideoURI(Uri.parse(path));
        videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {
                videoWidth = mediaPlayer.getVideoWidth();
                videoHeight = mediaPlayer.getVideoHeight();
                videoDuration = mediaPlayer.getDuration();
                Log.d("main", "setOnPreparedListener duration "+videoDuration);

                videoView.start();
                mediaPlayer.setLooping(true); //循环播放

                frameWidth = frameLayout.getWidth();
                frameHeight = frameLayout.getHeight();
                Log.d(TAG, "frame"+frameWidth+":"+frameHeight);
                Log.d(TAG, "video"+ videoWidth+":"+videoHeight);
//                Toast.makeText(MainActivity.this, frameWidth+":"+frameHeight, Toast.LENGTH_SHORT).show();

                //Get VideoView's current width and height
                int videoViewWidth = videoView.getWidth();
                int videoViewHeight = videoView.getHeight();

                float xScale = (float) videoViewWidth / videoWidth;
                float yScale = (float) videoViewHeight / videoHeight;

                //For Center Crop use the Math.max to calculate the scale
                //float scale = Math.max(xScale, yScale);
                //For Center Inside use the Math.min scale.
                //I prefer Center Inside so I am using Math.min
                scale = Math.min(xScale, yScale);

                float scaledWidth = scale * videoWidth;
                float scaledHeight = scale * videoHeight;

                //Set the new size for the VideoView based on the dimensions of the video
                ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
                layoutParams.width = (int)scaledWidth;
                layoutParams.height = (int)scaledHeight;
                videoView.setLayoutParams(layoutParams);

                videoView.invalidate();
                videoX = (frameWidth-layoutParams.width)/2;
                videoY = (frameHeight-layoutParams.height)/2;
                cropView.setCropRect(new RectF(videoX, videoY, videoX+layoutParams.width, videoY+layoutParams.height));
                cropView.setVisibility(View.VISIBLE);

                Log.d(TAG, "scaledWidth "+scaledWidth+" scaledHeight "+scaledHeight);
                Log.d(TAG, "video after set params");
                Log.d(TAG, "videoView"+ videoView.getWidth()+":"+videoView.getHeight());
                Log.d(TAG, "videoView getx "+ videoView.getX()+" and getY "+videoView.getY());
            }
        });
    }

    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.back){
            finish();
        }else if(view.getId()==R.id.btn_save){

            //添加友盟事件统计
            MyUtils.addUmengEvent(VideoRemoveWaterActivity.this,"video_remove_watermark_save","视频去水印保存");

            RectF rect = cropView.getCropRect();
            int x = (int) rect.left;
            int y = (int) rect.top;
            int width = (int) (rect.right-rect.left);
            int height = (int) (rect.bottom-rect.top);
            Log.d(TAG, x+","+y+"and "+width+"x"+height);
            int trueX = (int) ((rect.left-videoView.getX())/scale);
            int trueY = (int) ((rect.top-videoView.getY())/scale);
            int trueWidth = (int) (width/scale);
            int trueHeight = (int) (height/scale);
            Log.d(TAG, trueX+","+trueY+"and "+width+"x"+height);

            //解决边界问题
            trueX = trueX>0?trueX:1;
            trueY = trueY>0?trueY:1;
            if((trueX+trueWidth)>=videoWidth){
                trueWidth = videoWidth-trueX-1;
            }
            if((trueY+trueHeight)>videoHeight){
                trueHeight = videoHeight-trueY-1;
            }
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(100);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setTitle("正在处理");

            mProgressDialog.show();
            //去水印ffmpeg -i logo.mp4 -filter_complex "delogo=x=100:y=100:w=100:h=100:show=1" delogo.mp4
            out = VideoUtil.VIDEO_SLIDE_DIR+"/"+System.currentTimeMillis()+".mp4";
            //show=1 绿色边框
            //-i 1.jpg -vf "movie=2.jpg,scale=150:183[watermask];[in][watermask] overlay=100:100[out]" -y 3.jpg
//            String cmd = String.format("-i %s -filter_complex delogo=x=%s:y=%s:w=%s:h=%s:show=0 %s", path, trueX+"", trueY+"", trueWidth+"", trueHeight+"", out);
            trueX = trueX==0?1:trueX;
            trueY = trueY==0?1:trueY;
            if((trueX+trueWidth)>=videoWidth){
                trueWidth = videoWidth-trueX-1;
            }
            if((trueY+trueHeight)>=videoHeight){
                trueHeight = videoHeight-trueY-1;
            }
            String cmd = String.format("ffmpeg -i %s -filter_complex delogo=x=%s:y=%s:w=%s:h=%s:show=0 -preset superfast %s", path, trueX+"", trueY+"", trueWidth+"", trueHeight+"", out);
            int duration = VideoUtil.getDuration(this, path);
            Log.d(TAG, "duration "+duration);
            Log.d(TAG, "cmd "+cmd);

            String[] commands = cmd.split(" ");
            try {
                RxFFmpegInvoke.getInstance().runCommandRxJava(commands).subscribe(new RxFFmpegSubscriber() {
                    @Override
                    public void onFinish() {
                        Log.i("去水印保存","EpEditor.execCmd onSuccess");
                        mHandler.sendEmptyMessage(MSG_SUCCESS);
                    }

                    @Override
                    public void onProgress(int progress, long progressTime) {
                        Log.i("去水印保存","EpEditor.execCmd onProgress "+progress);
                        Message msg = new Message();
                        Bundle data = new Bundle();
                        data.putFloat("progress", progress);
                        msg.setData(data);
                        msg.what = MSG_PROGRESS;
                        mHandler.sendMessage(msg);

                    }

                    @Override
                    public void onCancel() {
                        Log.i("去水印保存","EpEditor.execCmd onFailure");
                        mHandler.sendEmptyMessage(MSG_CANCLE);
                    }

                    @Override
                    public void onError(String message) {
                        Log.i("去水印保存","EpEditor.execCmd onFailure");
                        mHandler.sendEmptyMessage(MSG_FAIL);
                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public static final int MSG_SUCCESS = 101;
    public static final int MSG_FAIL = 102;
    public static final int MSG_PROGRESS = 103;
    private static final int MSG_CANCLE = 104;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==MSG_SUCCESS){
                Log.i("视频去水印","去水印完成，跳转");
                Toast.makeText(VideoRemoveWaterActivity.this, "处理完成", Toast.LENGTH_SHORT).show();
                MyArt art = new MyArt();
                art.setHeight(videoHeight);
                art.setWidth(videoWidth);
                art.setCreate_time(System.currentTimeMillis()+"");
                art.setPath(out);
                art.setType(1);
                art.save();
                if(mProgressDialog.isShowing()){
                    mProgressDialog.dismiss();
                }
//                FileUtil.ablumUpdate(VideoRemoveWaterActivity.this, art.getPath(),1);//更新相册
                Intent intent = new Intent(VideoRemoveWaterActivity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, out);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", videoWidth);
                intent.putExtra("height", videoHeight);
                intent.putExtra("type", "1");
                startActivity(intent);
                finish();

            }else if(msg.what==MSG_FAIL){
                Toast.makeText(VideoRemoveWaterActivity.this, "处理失败", Toast.LENGTH_SHORT).show();
                if(mProgressDialog.isShowing()){
                    mProgressDialog.dismiss();
                }
            }else if(msg.what==MSG_PROGRESS){
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }else if(msg.what==MSG_CANCLE){
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("VideoRemoveWaterActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("VideoRemoveWaterActivity");//统计页面
        MobclickAgent.onPause(this);
    }
}
